var fs = null;
module.exports = {
    init: function init() {
        if(CC_WECHATGAME)
        fs = wx.getFileSystemManager();
    },
    readDir: function readDir(dir, cb) {
      if(CC_WECHATGAME){
          console.log('readDir:',dir);
          var acyn = new CCAsync()
          var files = [];
          var folds = [];
          var filefuncs = [];
          var self = this
          fs.readdir({
            dirPath: dir,
            success: function (res) {
              for (var i = 0; i < res.files.length; i++) {
                var file = dir + '/' + res.files[i];
                console.log('file:',file)
                var stat = fs.statSync(file)
                var fileInfo = {
                  name: res.files[i],
                  path:file,
                  size: 0
                };
                if (stat.isFile()) {
                  files.push(fileInfo);
                  filefuncs.push(function (scb) {
                    self.getFileInfo(this, scb);
                  }.bind(fileInfo))
                } else {
                  folds.push(file);
                }
              }
              if (filefuncs.length > 0) {
                acyn.parallel(filefuncs, function () {
                  console.log('文件夹读取完')
                  cb(null, files,folds);
                })
              } else {
                cb(null, files, folds);
              }
            },
            fail: function (res) {
              cb(res, null, null)
            }
          })
      } else {
          cb(null, [ {
              name: "file1.txt",
              size: 12600
            }, {
              name: "file2.txt",
              size: 36e3
            } ], [ "main" ]);
      }
    },
    getFileInfo(fileInfo,cb){
      fs.getFileInfo({
          filePath: fileInfo.path,
          success: function success(res) {
            console.log("fileInfo:", fileInfo.path, res);
            fileInfo.size = res.size;
            cb(null,fileInfo);
          },
          fail: function fail(res) {
            file.size = 0;
            cb(res,null);
          }
        });
    },
    readFile: function readFile(path, cb) {
        if(CC_WECHATGAME){
          fs.readFile({
              filePath: path,
              encoding: 'utf8',
              success:(res)=>{
                // console.log('读取出的数据:',path,'\n',res.data);
                cb(res.data)
              },
              fail:()=>{
                cb(null)
              }
            })
        } else {
            cc.loader.loadRes('config', cc.RawAsset,function(err,res){
              cb(JSON.stringify(res));
            })
          // cb("asdlkjfhaoiudshyfiausdy fiauysdf");
        }
    },
    removeFile:function(path,cb1){
      fs.unlink({
          filePath: path,
          success: function (res) {
            cb1(null,1)
          }.bind(this),
          fail: function (e) {
            cb1(null)
          }
      })
    }
}